﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

public class CardGameWindow : SingletonBaseWindow<CardGameWindow> {

    private CardEventListen cardeventlisten;


    public Button _Btn_Back { get; set; }


    public Transform _Card_level_1 { get;  set; }

    public Transform _Card_level_2 { get; set; }

    public Transform _hand_click { get; set; }

    public System.Action GameCarryOut;

    private int CompleteCount = 0;

    public int CompleteTime = 0;

    private List<Transform> cards;

    public List<Transform> Flip_Cards = new List<Transform>();

    public List<Vector3> startpos = new List<Vector3>();

    public List<Transform> FirstEnterGameCards = new List<Transform>();

    private int EnterGameTime = 0;

    private bool IsClickFirstCard = false;



    protected override void OnOpen(params object[] paramArray)
    {
        base.OnOpen(paramArray);

        Debug.Log("--------------------------------- CardGameStart");

        
    }

    protected override void AddListeners()
    {
        base.AddListeners();
        
        foreach (Transform Card in _Card_level_1.GetChild(0))
        {
            cardeventlisten = Card.AddComponentEx<CardEventListen>();
            Card.AddComponentEx<UIInputHandler>().OnClick += cardeventlisten.OnClickCard;
        }
        foreach (Transform Card in _Card_level_1.GetChild(1))
        {
            cardeventlisten = Card.AddComponentEx<CardEventListen>();
            Card.AddComponentEx<UIInputHandler>().OnClick += cardeventlisten.OnClickCard;
        }
        foreach (Transform Card in _Card_level_2.GetChild(0))
        {
            cardeventlisten = Card.GetChild(0).AddComponentEx<CardEventListen>();
            Card.GetChild(0).AddComponentEx<UIInputHandler>().OnClick += cardeventlisten.OnClickCard;
        }
        foreach (Transform Card in _Card_level_2.GetChild(0))
        {
            foreach (Transform card in Card.GetChild(1))
            {
                cardeventlisten = card.AddComponentEx<CardEventListen>();
                card.AddComponentEx<UIInputHandler>().OnClick += cardeventlisten.OnClickCard;
            }
        }
        foreach (Transform Card in _Card_level_2.GetChild(1))
        {
            cardeventlisten = Card.GetChild(0).AddComponentEx<CardEventListen>();
            Card.GetChild(0).AddComponentEx<UIInputHandler>().OnClick += cardeventlisten.OnClickCard;
        }
        foreach (Transform Card in _Card_level_2.GetChild(1))
        {
            foreach (Transform card in Card.GetChild(1))
            {
                cardeventlisten = card.AddComponentEx<CardEventListen>();
                card.AddComponentEx<UIInputHandler>().OnClick += cardeventlisten.OnClickCard;
            }
        }



        _Btn_Back.onClick.AddListener(CardGameManarge.Instance.OnExitGame);
        EventBus.Instance.AddEventHandler(EventID.ON_CARD_GAME_CARRY_OUT,OnCarryOut);
    }


    
    protected override void RemoveListensers()
    {
        base.RemoveListensers();
        foreach (Transform Card in _Card_level_1.GetChild(0))
        {
            //Component.GetComponent<CardEventListen>();
            CardGameManarge.Instance.DestroyComponent(Card.GetComponent<CardEventListen>());
            Card.GetComponent<UIInputHandler>().OnClick -= cardeventlisten.OnClickCard;
                       
        }
        foreach (Transform Card in _Card_level_1.GetChild(1))
        {
            //Component.GetComponent<CardEventListen>();
            CardGameManarge.Instance.DestroyComponent(Card.GetComponent<CardEventListen>());
            Card.GetComponent<UIInputHandler>().OnClick -= cardeventlisten.OnClickCard;
        }
        foreach (Transform Card in _Card_level_2.GetChild(0))
        {
            CardGameManarge.Instance.DestroyComponent(Card.GetComponent<CardEventListen>());
            Card.GetChild(0).AddComponentEx<UIInputHandler>().OnClick -= cardeventlisten.OnClickCard;
        }
        foreach (Transform Card in _Card_level_2.GetChild(0))
        {
            foreach (Transform card in Card.GetChild(1))
            {
                CardGameManarge.Instance.DestroyComponent(card.GetComponent<CardEventListen>());
                card.AddComponentEx<UIInputHandler>().OnClick -= cardeventlisten.OnClickCard;
            }
        }
        foreach (Transform Card in _Card_level_2.GetChild(1))
        {
            CardGameManarge.Instance.DestroyComponent(Card.GetComponent<CardEventListen>());
            Card.GetChild(0).AddComponentEx<UIInputHandler>().OnClick -= cardeventlisten.OnClickCard;
        }
        foreach (Transform Card in _Card_level_2.GetChild(1))
        {
            foreach (Transform card in Card.GetChild(1))
            {
                CardGameManarge.Instance.DestroyComponent(card.GetComponent<CardEventListen>());
                card.AddComponentEx<UIInputHandler>().OnClick -= cardeventlisten.OnClickCard;
            }
        }
        _Btn_Back.onClick.RemoveListener(CardGameManarge.Instance.OnExitGame);
        EventBus.Instance.RemoveEventHandler(EventID.ON_CARD_GAME_CARRY_OUT, OnCarryOut);
    }


    protected override void OnUpdate()
    {
        base.OnUpdate();
        if (FirstEnterGameCards.Count == 0)
        {
            return;
        }
        //Debug.LogError(FirstEnterGameCards[0].rotation.y);
        if (FirstEnterGameCards[0].rotation.y != 0 && IsClickFirstCard)
        {
            Debug.LogError("-------------------------------------- IsClickFirstCard");
            FirstEnterGameCards[1].DORotate(new Vector3(0,0,0),0.01f);
            _hand_click.position = FirstEnterGameCards[1].position + new Vector3(0,-10,-50);
            IsClickFirstCard = false;
        }
        if (EnterGameTime == 1)
        {
            foreach (Transform card in cards)
            {
                card.DORotate(new Vector3(0,0,0),0.01f);
            }
            cards.Add(FirstEnterGameCards[0]);
            cards.Add(FirstEnterGameCards[1]);
            FirstEnterGameCards.Clear();
            EnterGameTime++;
        }
        if (FirstEnterGameCards.Count != 0 && FirstEnterGameCards[0].rotation.y != 0)
        {
            if (FirstEnterGameCards[1].rotation.y > 0.2)
            {
                _hand_click.gameObject.SetActive(false);
            }
            
        }
    }

    public void StartGame(int GameLevel, int CardCount, List<Sprite> sprite, List<int> RandomNumber, System.Action GameCarryOut = null)
    {
        //Debug.Log("22222");
        //Debug.Log(_Card.name);
        this.cards = SetCard(CardCount);
        foreach (Transform card in cards)
        {
            startpos.Add(card.position);
        }
        CardGameManarge.Instance.SetStartPos(CardCount,startpos);
        SetScale(cards);
        AudioManager.Instance.PlaySound("study_cardgame/study_cardgame_sound/603090103");
        TimerManager.Instance.AddTimer(4f, () =>
        {
            SetStartRotate(cards);
        });
        this.SetCardsSprite(this.cards, RandomNumber, sprite);
        this.GameCarryOut = GameCarryOut;
        
        foreach (Transform card in this.cards)
        {
           
            if (card.gameObject.GetComponent<CardEventListen>() == null)
            {
                card.AddComponentEx<CardEventListen>();
                //return;
            }
            card.gameObject.GetComponent<CardEventListen>().enabled = true;
            card.gameObject.GetComponent<CardEventListen>().IsClick = false;
        }
        TimerManager.Instance.AddTimer(5.02f,()=>
        {
        if (EnterGameTime == 0 && !PlayerPrefs.HasKey("FirstEnterGame"))
            {
                FirstEnterGameCards.Add(cards[0]);
                foreach (Transform card in cards)
                {
                    if (card.GetChild(0).gameObject.GetComponent<Image>().sprite.name == FirstEnterGameCards[0].GetChild(0).gameObject.GetComponent<Image>().sprite.name && card.gameObject != FirstEnterGameCards[0].gameObject)
                    {
                        FirstEnterGameCards.Add(card);
                    }
                    card.gameObject.transform.DORotate(new Vector3(0,0.01f,0),0.01f);
                    
                }
                _hand_click.position = FirstEnterGameCards[0].position + new Vector3(0,-10,-50);
                _hand_click.gameObject.SetActive(true);
                FirstEnterGameCards[0].DORotate(new Vector3(0,0,0),0.01f);
                IsClickFirstCard = true;
                
            }
        });
        
    }

    public void StartGame(int GameLevel, int CardCount, List<Sprite> NumberSprite, List<Sprite> ComponentsSprite, List<int> RandomNumber, System.Action GameCarryOut = null)
    {
        //int x = 0;
        
        this.cards = SetCard(GameLevel,NumberSprite,ComponentsSprite,CardCount);
        List<int> RandomNmb = CardGameManarge.Instance.RandomNumbers(CardCount, CardCount);
        foreach (Transform card in cards)
        {
            startpos.Add(card.position);
        }
        for (int i = 0; i < CardCount; i++)
        {
            cards[i].position = startpos[RandomNmb[i]];
        }
        SetScale(cards);
        AudioManager.Instance.PlaySound("study_cardgame/study_cardgame_sound/603090103");
        TimerManager.Instance.AddTimer(4f, () =>
        {
            SetStartRotate(cards);
        });
        this.GameCarryOut = GameCarryOut;
        foreach (Transform card in this.cards)
        {
            if (card.gameObject.GetComponent<CardEventListen>() == null)
            {
                card.AddComponentEx<CardEventListen>();
                //return;
            }
            card.gameObject.GetComponent<CardEventListen>().enabled = true;
            card.gameObject.GetComponent<CardEventListen>().IsClick = false;
        }
    }




    public void OnCarryOut()
    {
        if (CardGameManarge.Instance.GetGameLevel() == 1)
        {
            //foreach (Transform Card in cards)
            //{
            //Debug.LogError(Flip_Cards.Count);
            
            if (Flip_Cards.Count == 0)
            {
                return;
            }
            if (this.Flip_Cards[0].GetChild(0).gameObject.GetComponent<Image>().sprite.name == this.Flip_Cards[1].GetChild(0).gameObject.GetComponent<Image>().sprite.name)
            {
                CarryOutEffect(Flip_Cards);
                foreach (Transform Flip_Card in this.Flip_Cards)
                {
                    Flip_Card.gameObject.GetComponent<CardEventListen>().enabled = false;
                    
                    //this.cards.Remove(Flip_Card);
                    AudioClip audio = ResourceManager.Instance.GetResource("study_cardgame/study_cardgame_sound/603090101",typeof(AudioClip),enResourceType.Sound,false).m_content as AudioClip;
                    AudioManager.Instance.PlaySound(audio);
                    
                    CompleteTime++;
                    if (EnterGameTime == 0 && !PlayerPrefs.HasKey("FirstEnterGame"))
                    {
                        
                        cards.Remove(FirstEnterGameCards[0]);
                        cards.Remove(FirstEnterGameCards[1]);
                        EnterGameTime++;
                        PlayerPrefs.SetInt("FirstEnterGame",10);
                    }
                    //Debug.LogError(CompleteTime);
                    if (CompleteTime == cards.Count)
                    {
                        TimerManager.Instance.AddTimer(1.5f, () =>
                        {
                            this.GameCarryOut();
                        });
                    }
                }
                Flip_Cards.Clear();
                this.CompleteCount = 0;
                CardGameManarge.Instance.SetIsClick(true);
                //cardeventlisten.IsClick = false;
                return;
            }
            else
            {
                foreach (Transform Flip_Card in this.Flip_Cards)
                {
                    Flip_Card.gameObject.GetComponent<CardEventListen>().IsClick = false;
                    Flip_Card.DORotate(new Vector3(0, 0, 0), 1f);
                }
                AudioClip audio = ResourceManager.Instance.GetResource("study_cardgame/study_cardgame_sound/603090102", typeof(AudioClip), enResourceType.Sound, false).m_content as AudioClip;
                AudioManager.Instance.PlaySound(audio);
                Flip_Cards.Clear();
                this.CompleteCount = 0;
                CardGameManarge.Instance.SetIsClick(true);

                //CardGameManarge.Instance.CloseCardClick();
                return;
            }
            // }
        }
        else
        {
            if (this.Flip_Cards[0].parent == this.Flip_Cards[1].parent.parent || this.Flip_Cards[1].parent == this.Flip_Cards[0].parent.parent)
            {
                CarryOutEffect(Flip_Cards);
                foreach (Transform Flip_Card in this.Flip_Cards)
                {
                    Flip_Card.gameObject.GetComponent<CardEventListen>().enabled = false;
                    //this.cards.Remove(Flip_Card);
                    AudioClip audio = ResourceManager.Instance.GetResource("study_cardgame/study_cardgame_sound/603090101", typeof(AudioClip), enResourceType.Sound, false).m_content as AudioClip;
                    AudioManager.Instance.PlaySound(audio);
                    CompleteTime++;
                    if (CompleteTime == cards.Count)
                    {
                        TimerManager.Instance.AddTimer(0.5f,()=> 
                        {
                            this.GameCarryOut();
                        });
                        
                    }
                }
                Flip_Cards.Clear();
                this.CompleteCount = 0;
                CardGameManarge.Instance.SetIsClick(true);
                cardeventlisten.IsClick = false;
                return;
            }
            else
            {
                foreach (Transform Flip_Card in this.Flip_Cards)
                {
                    Flip_Card.gameObject.GetComponent<CardEventListen>().IsClick = false;
                    Flip_Card.DORotate(new Vector3(0, 0, 0), 1f);
                }
                AudioClip audio = ResourceManager.Instance.GetResource("study_cardgame/study_cardgame_sound/603090102", typeof(AudioClip), enResourceType.Sound, false).m_content as AudioClip;
                AudioManager.Instance.PlaySound(audio);
                Flip_Cards.Clear();
                this.CompleteCount = 0;
                CardGameManarge.Instance.SetIsClick(true);

                //CardGameManarge.Instance.CloseCardClick();
                return;
            }


        }
    }




    public void OnExitGame()
    {
        
        CardGameManarge.Instance.ClearData();
        SceneLoader.Instance.LoadScene(SceneLoader.MainScene);
        GameStateManager.Instance.GotoState(GameStateName.MAIN_STATE);
        _Btn_Back.onClick.RemoveListener(CardGameManarge.Instance.OnExitGame);

    }


    public List<Transform> SetCard(int CardCount)
    {
        
            List<Transform> Cards = new List<Transform>();
            if (CardCount == 6)
            {
                foreach (Transform card in _Card_level_1.GetChild(0))
                {
                    Cards.Add(card);
                }
                _Card_level_1.GetChild(0).gameObject.SetActive(true);
                return Cards;
            }
            if (CardCount == 8)
            {
                foreach (Transform card in _Card_level_1.GetChild(1))
                {
                    Cards.Add(card);
                }
                _Card_level_1.GetChild(1).gameObject.SetActive(true);
                return Cards;
            }
            return null;

    }

    public List<Transform> SetCard(int Gamelevel, List<Sprite> NumberSprite, List<Sprite> componentsSprite, int CardCount)
    {
        int i = 0;
        List<Transform> Numbers = new List<Transform>();
        List<Transform> NotNumbers = new List<Transform>();
        List<Transform> Components = new List<Transform>();
        List<string> SetNotNumber = new List<string>();
        foreach (Sprite sprite in NumberSprite)
        {
            SetNotNumber.Add(sprite.name.Split('0')[1]);
        }
        if (CardCount == 6)
        {
            _Card_level_2.GetChild(0).gameObject.SetActive(true);
            foreach (Transform card in _Card_level_2.GetChild(0))
            {
                
                cards.Add(card.GetChild(0));
                Numbers.Add(card.GetChild(0));
                NotNumbers.Add(card.GetChild(1));
            }
            foreach (Transform NotNumber in NotNumbers)
            {
                
                foreach (Transform item in NotNumber)
                {
                    
                    if (item.name + "(Clone)" == SetNotNumber[i])
                    {
                        //Debug.LogError(item.name);
                        //Debug.LogError(SetNotNumber[i]);
                        cards.Add(item);
                        Components.Add(item);
                        item.gameObject.SetActive(true);
                        
                    }
                    
                }
                i++;
            }

            for (int j = 0; j < Components.Count; j++)
            {
                foreach (Transform component in Components[j].GetChild(0))
                {
                    component.gameObject.GetComponent<Image>().sprite = componentsSprite[j];
                    component.gameObject.GetComponent<Image>().SetNativeSize();
                }
            }


            for (int j = 0; j < Numbers.Count; j++)
            {
                Numbers[j].GetChild(0).gameObject.GetComponent<Image>().sprite = NumberSprite[j];
                Numbers[j].GetChild(0).gameObject.GetComponent<Image>().SetNativeSize();
            }

            foreach (Transform card in cards)
            {
                card.gameObject.SetActive(true);
            }

            return cards;
        }

        if (CardCount == 8)
        {
            _Card_level_2.GetChild(1).gameObject.SetActive(true);
            foreach (Transform card in _Card_level_2.GetChild(1))
            {
                
                cards.Add(card.GetChild(0));
                Numbers.Add(card.GetChild(0));
                NotNumbers.Add(card.GetChild(1));
            }
            foreach (Transform NotNumber in NotNumbers)
            {
                
                foreach (Transform item in NotNumber)
                {
                    if (item.name + "(Clone)" == SetNotNumber[i])
                    {
                        
                        cards.Add(item);
                        Components.Add(item);
                        item.gameObject.SetActive(true);

                    }
                }
                i++;
            }

            for (int j = 0; j < Components.Count; j++)
            {
                foreach (Transform component in Components[j].GetChild(0))
                {
                    component.gameObject.GetComponent<Image>().sprite = componentsSprite[j];
                    component.gameObject.GetComponent<Image>().SetNativeSize();
                }
            }
            for (int j = 0; j < Numbers.Count; j++)
            {
                Numbers[j].GetChild(0).gameObject.GetComponent<Image>().sprite = NumberSprite[j];
                Numbers[j].GetChild(0).gameObject.GetComponent<Image>().SetNativeSize();
            }
            foreach (Transform card in cards)
            {
                card.gameObject.SetActive(true);
            }
            return cards;
        }

        
        return null;
    }
    


    public void SetCardsSprite(List<Transform> Cards,List<int> RandomNumber,List<Sprite> Cards_Sprite)
    {
        for (int i = 0; i < Cards.Count; i++)
        {
            Cards[RandomNumber[i]].GetChild(0).GetComponent<Image>().sprite = Cards_Sprite[i];
            //Cards[RandomNumber[i]].GetChild(0).GetComponent<Image>().SetNativeSize();
        }
    }


    public void CarryOutEffect(List<Transform> File_Cards)
    {
        List<Transform> Cards = File_Cards;
        foreach (Transform card in Cards)
        {
            //card.gameObject.GetComponent<RectTransform>().pivot = new Vector2(1f,0f);
            card.GetChild(2).gameObject.SetActive(true);
            card.DOScale(new Vector3(0.7f,0.7f,0.7f),0.1f);
            TimerManager.Instance.AddTimer(0.1f,()=> 
            {
                card.DOScale(new Vector3(1.2f, 1.2f, 1.2f), 0.1f);
            });
            TimerManager.Instance.AddTimer(0.2f,()=>
            {
                card.DOScale(new Vector3(0.6f, 0.6f, 0.6f), 0.1f);
            });
            TimerManager.Instance.AddTimer(0.3f, () =>
            {
                card.DOScale(new Vector3(1.1f, 1.1f, 1.1f), 0.1f);
            });
            TimerManager.Instance.AddTimer(0.4f, () =>
            {
                card.DOScale(new Vector3(0.7f, 0.7f, 0.7f), 0.1f);
            });
            TimerManager.Instance.AddTimer(0.5f, () =>
            {
                card.DOScale(new Vector3(1f, 1f, 1f), 0.1f);
            });
            TimerManager.Instance.AddTimer(1.2f, () =>
            {
                card.GetChild(2).gameObject.SetActive(false);
            });
        }
    }



    //public int Index(int i)
    //{
    //    int x = i;
    //    int j = 0;
    //    if (x <= 0)
    //    {
    //        return 0;
    //    }
    //    else
    //    {
    //        return j = (int)Mathf.Ceil(x / 2);
    //    }
    //}

    public int Completecount
    {
        get
        {
            return CompleteCount;
        }

        set
        {
            CompleteCount = value;
        }
    }

    public void SetFlip_Card(Transform Card)
    {
        Flip_Cards.Add(Card);
    }

    public void SetScale(List<Transform> cards)
    {
        foreach (Transform card in cards)
        {
            card.gameObject.GetComponent<CardEventListen>().IsClick = true;
            card.DOScale(new Vector3(1, 1, 1), 0.8f);
            
        }
    }

    public void SetStartRotate(List<Transform> cards)
    {
        foreach (Transform item in cards)
        {
            item.gameObject.GetComponent<CardEventListen>().IsClick = false;
            item.DORotate(new Vector3(0, 0, 0), 1f);
        }
    }

    public void SetDatatoStart(List<Transform> cards)
    {
        if (cards == null)
        {
            return;
        }
        
        foreach (Transform card in cards)
        {
            card.gameObject.SetActive(false);
            card.localScale = new Vector3(0.01f,0.01f,0.01f);
            card.localRotation = Quaternion.Euler(new Vector3(0,180,0));
            
            //card.gameObject.GetComponent<CardEventListen>().IsClick = false;
        }
    }


    public void ClearData()
    {
        SetDatatoStart(cards);
        if (cards != null)
        {
            if (cards.Count == 6)
            {
                _Card_level_1.GetChild(0).gameObject.SetActive(false);
            }
            if (cards.Count == 8)
            {
                _Card_level_1.GetChild(1).gameObject.SetActive(true);

            }
            foreach (Transform card in cards)
            {
                card.gameObject.GetComponent<CardEventListen>().IsClick = false;
            }
            for (int i = 0; i < cards.Count; i++)
            {
                cards[i].position = startpos[i];
            }
            this.cards.Clear();
            this.startpos.Clear();
        }
       
        //Flip_Cards.Clear();
        this.CompleteTime = 0;
        this.FirstEnterGameCards.Clear();
        this._hand_click.gameObject.SetActive(false);
        this.CompleteCount = 0;
        this.Flip_Cards = new List<Transform>();
    }

   



}
